package com.dts.backproject.util;

import com.dts.backproject.config.COSConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class COSUploader {
    
    @Autowired
    private COSConfig cosConfig;
    
    /**
     * 上传文件到腾讯云COS
     * @param file 要上传的文件
     * @param folder 存储文件夹，如 "avatars", "images" 等
     * @return 文件的访问URL
     */
    public String uploadFile(MultipartFile file, String folder) {
        COSClient cosClient = null;
        try {
            // 1. 初始化用户身份信息
            COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
            
            // 2. 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegion()));
            
            // 3. 生成cos客户端
            cosClient = new COSClient(cred, clientConfig);
            
            // 4. 生成存储桶名称
            String bucket = cosConfig.getBucketName();
            
            // 5. 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString() + extension;
            String key = folder + "/" + fileName;
            
            // 6. 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file.getInputStream(), null);
            
            // 7. 上传文件
            cosClient.putObject(putObjectRequest);
            
            // 8. 获取文件URL
            String url = "https://" + bucket + ".cos." + cosConfig.getRegion() + ".myqcloud.com/" + key;
            System.out.println("文件上传成功，URL: " + url);
            
            return url;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 9. 关闭客户端
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
    }
    
    /**
     * 上传文件到腾讯云COS（使用File对象）
     * @param file 要上传的文件
     * @param folder 存储文件夹
     * @return 文件的访问URL
     */
    public String uploadFile(File file, String folder) {
        COSClient cosClient = null;
        try {
            // 1. 初始化用户身份信息
            COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
            
            // 2. 设置bucket的区域
            ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegion()));
            
            // 3. 生成cos客户端
            cosClient = new COSClient(cred, clientConfig);
            
            // 4. 生成存储桶名称
            String bucket = cosConfig.getBucketName();
            
            // 5. 生成唯一文件名
            String originalFilename = file.getName();
            String extension = "";
            if (originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString() + extension;
            String key = folder + "/" + fileName;
            
            // 6. 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file);
            
            // 7. 上传文件
            cosClient.putObject(putObjectRequest);
            
            // 8. 获取文件URL
            String url = "https://" + bucket + ".cos." + cosConfig.getRegion() + ".myqcloud.com/" + key;
            System.out.println("文件上传成功，URL: " + url);
            
            return url;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        } finally {
            // 9. 关闭客户端
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
    }
}